<template>
  <Dialog v-model="dialogVisible" title="模板上传">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="140px"
    >
      <el-form-item label="上传" prop="customerNames">
        <el-upload
          class="upload-demo"
          action="#"
          :on-remove="handleRemove"
          accept=".xls,.xlsx"
          :file-list="importFileList"
          :on-change="beforeUpload"
          :auto-upload="false"
          :limit="1"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
            <div class="flex flex-col">
              <div class="el-upload__tip" style="color: red">请按照模板填好上传</div>
              <div class="el-upload__tip"
                >仅允许导入 xls、xlsx 格式文件。<el-button type="text" @click="downloadTmp"
                  >下载模板</el-button
                >
              </div>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <!--      <el-form-item label="请选择部门" prop="companyId">
          <el-tree-select
                  v-model="formData.companyId"
                  ref="treeRef"
                  :data="deptList"
                  :expand-on-click-node="false"
                  :props="defaultProps"
                  default-expand-all
                  highlight-current
                  node-key="id"
          />
      </el-form-item>-->
      <el-form-item label="归属员工" prop="ownerUserId">
        <el-select v-model="formData.ownerUserId" value-key="id" placeholder="请选择员工">
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { CustomerApi } from '@/api/crm/crmcustomer'
import * as DeptApi from '@/api/system/dept'
import { handleTree } from '@/utils/tree'
import * as UserApi from '@/api/system/user'
import download from '@/utils/download'
defineOptions({ name: 'SystemSmsTemplateSendForm' })
const emit = defineEmits(['success']) // 定义可触发的事件
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const userList = ref([])
const importFileList = ref([])
// 发送短信表单相关
const formData = ref({
  companyId: '',
  ownerUserId: ''
})
const formRules = reactive({
  ownerUserId: [{ required: true, message: '归属不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const deptList = ref<Tree[]>([]) // 树形结构
/** 获得部门树 */
const getTree = async () => {
  const res = await DeptApi.getSimpleDeptList()
  deptList.value = []
  deptList.value.push(...handleTree(res))
}
const handleRemove = (file, fileList) => {
  console.log(file, fileList)
  /*if(importFileList.length){
        const index = importFileList.value.indexOf(file);
        const newFileList = importFileList.value.slice();
        newFileList.splice(index, 1);
        importFileList.value = newFileList;
    }*/
}

const beforeUpload = (file: any) => {
  importFileList.value = [...importFileList.value, file]
  return false
}
const downloadTmp = async () => {
  const data = await CustomerApi.downloadImportCustomerTemplate({})
  download.excel(data, '客户导入模板.xls')
}

const open = async (customers, type) => {
  dialogVisible.value = true
  // 设置数据
  formLoading.value = true
  formData.value.ownerUserId = ''
  try {
    userList.value = await UserApi.getUserListAllSimple({})
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    await CustomerApi.importCustomer({
      file: importFileList.value[0].raw,
      ownerUserId: formData.value.ownerUserId
    }).then((res) => {
      const disposition = res.headers['content-disposition']
      const successNum = Number(res.headers['x-success-num'])
      if (successNum > 0) {
        importFileList.value = []
        message.success('已成功导入' + successNum + '数据。')
      } else {
        importFileList.value = []
        message.error('请查看失败原因' + successNum + '数据。')
        let fileName = '导出数据.xlsx'
        const filenameMatch = disposition.match(/filename\*?=(?:UTF-8''|)(.+)/)
        if (filenameMatch && filenameMatch[1]) {
          fileName = decodeURIComponent(filenameMatch[1])
          download.excel(res.data, fileName)
        }
      }
    })
    message.success('提交发送成功！发送结果，见发送日志')
    dialogVisible.value = false
    emit('success')
  } catch (e) {
    console.log(e)
  } finally {
    formLoading.value = false
  }
}

onMounted(async () => {
  await getTree()
})
</script>
